import { Module, ActionTree, MutationTree } from 'vuex'
import { AppState, RootStateTypes } from '../interface/index'
import { login, refreshLogin } from '@/api/login'
import { setSession, clearSession, getSession } from '@/utils/storage'
import router from '@/router'

const state: AppState = {
  requestCount: {
    count: 0,
    time: 0
  }, // 过期请求次数
  token: '', // token
  refreshToken: '', // refreshToken
  userInfo: {}, // 用户信息
  menuList: [], // 静态路由菜单栏 目前暂时未使用，用的是routeList中的routeList
}

const mutations: MutationTree<AppState> = {
  increment(state: AppState, clearFlag: boolean = false) {
    if (!clearFlag) {
      state.requestCount.count++
      state.requestCount.time = Date.now()
    } else {
      state.requestCount.count = 0
      state.requestCount.time = 0
    }
  },
  // 设置token
  SET_TOKEN: (state: AppState, token: string) => {
    state.token = token
  },
  SET_REFRESHTOKEN: (state: AppState, refreshToken: string) => {
    state.refreshToken = refreshToken
  },
  // 设置用户信息
  SET_USERINFO: (state: AppState, userInfo: any) => {
    state.userInfo = userInfo
  },
  logouts() {
    router.push({
      path: '/login'
    })
  }
}

const actions: ActionTree<AppState, RootStateTypes> = {
  /**
   * 登录action
   * @param param0
   * @param params
   * @returns
   */
  login({ dispatch, commit }, params) {
    return new Promise((resolve, reject) => {
      login(params)
        .then(async (res) => {
          const { data } = res
          commit('SET_TOKEN', data.accessToken)
          commit('SET_REFRESHTOKEN', data.keepLoginToken)
          // commit('SET_USERINFO', data)
          // const routeMenuList = Utils.arrayToTree(data.menus || [], 0)
          // if (routeMenuList.length > 0) {
          //   dispatch('routesList/setRoutesList', (routeMenuList as any)[0].children, { root: true })
          // }
          setSession('token', data.accessToken)
          setSession('refreshToken', data.keepLoginToken)
          resolve(data)
        })
        .catch((err) => {
          console.log(err, 969)

          reject(err)
        })
    })
  },
  /**
   * 退出action
   * @param param0
   * @param params
   */
  logout({ dispatch, commit }) {
    commit('SET_TOKEN', '')
    commit('SET_REFRESHTOKEN', '')
    commit('SET_USERINFO', {})
    commit('SET_PLAT')
    dispatch('routesList/setRoutesList', [], { root: true })
    commit('increment', true)
    clearSession()
    commit('logouts')
  },
  /**
   * 过期刷新action
   * @param param0
   * @returns
   */
  refreshToken({ dispatch, commit }) {
    return new Promise((resolve, reject) => {
      let params = {
        refreshToken: getSession('refreshToken')
      }

      refreshLogin(params)
        .then((res: any) => {
          console.log(res, 'res')

          if (res.code === 'success' || res.code === 1) {
            commit('SET_TOKEN', res.data)
            setSession('token', res.data)
            resolve(res.data)
          }
        })
        .catch((err) => {
          dispatch('logout')
        })
    })
  }
}

const app: Module<AppState, RootStateTypes> = {
  namespaced: true,
  state,
  mutations,
  actions
}

export default app
